/*
 * @Description:
 * @Author: william
 * @Date: 2024-08-22 11:47:45
 * @LastEditors: william
 * @LastEditTime: 2025-09-16 15:14:24
 */
// src/store/user.js
import { getUmsToken, setUmsToken, removeUmsToken } from '@/utils/cookies'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref(getUmsToken())
    const userInfo = ref({})

    const setToken = (data, expires) => {
      token.value = data
      setUmsToken(data, expires)
    }

    const getUserInfo = _ => {
      return g_api.user.apiGetLoginUser().then(({ code, data }) => {
        if (code === 200 && data) {
          setUserInfo(data)
        }
        return data
      })
    }

    const setUserInfo = data => {
      userInfo.value = data
    }
    const setLogOut = _ => {
      token.value = ''
      removeUmsToken()
      userInfo.value = {}
      uni.reLaunch({
        url: '/pages/login/index'
      })
    }
    return {
      token,
      userInfo,
      setToken,
      getUserInfo,
      setUserInfo,
      setLogOut
    }
  },
  {
    // persist: true // 配置持久化
    persist: [
      {
        key: 'user-store', // 自定义存储键名
        // storage: localStorage, // 默认是 localStorage,可以改为 sessionStorage,可全局配置
        pick: ['userInfo']
      }
    ]
  }
)
export function useOutsideUserStore() {
  return useUserStore(g_store)
}
